<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Customer</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
</head>
<body>
<div class="layuimini-container" id="app">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>充值客户留存</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="" lay-filter="table-search">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">选择区服:</label>
                            <div class="layui-input-inline">
                                <select name="gameArea" class="layui-select">
                                    <option v-for="(item,index) in services" :value="item.server_id" :selected="index==0">{{item.name}}</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">查询时间</label>
                            <div class="layui-input-inline">
                                <input type="text" name="createDateBegin" id="createTime0"
                                       placeholder="开始时间" autocomplete="off" class="layui-input" />
                                <input type="text" name="createDateEnd" id="createTime1"
                                       placeholder="截止时间" autocomplete="off" class="layui-input" />
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i>搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <div style="margin-top:64px;">
            <table>
                <tr>
                    <th>次日留存率：<span>{{ nextDayRetention }}%</span></th>
                    <th>三日留存率：<span>{{ thirdDayRetention }}%</span></th>
                    <th>七日留存率：<span>{{ seventhDayRetention }}%</span></th>
                    <th>十五日留存率：<span>{{ fifteenthDayRetention }}%</span></th>
                    <th>三十日留存率：<span>{{ thirtiethDayRetention }}%</span></th>
                </tr>
            </table>
        </div>
        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
    </div>
</div>

<style>
    span.percentage {
        color: #03a9f4;
    }
</style>
<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/common.js?v=5" charset="utf-8"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2"></script> <!--确保引入Vue.js -->
<script>
    function calculatePercentage(num, total) { // 计算2个数的百分比
        if (total === 0) {
            return 0;
        }
        const percentage = (num / total) * 100;
        return parseFloat(percentage.toFixed(2));
    }

    new Vue({
        el: "#app",
        data: {
            services: JSON.parse(localStorage.getItem('services')),
            nextDayRetention: 0,
            thirdDayRetention: 0,
            seventhDayRetention: 0,
            fifteenthDayRetention: 0,
            thirtiethDayRetention: 0,
        },
        methods: {
            calculateRetentionRates(data) {
                // 1. 找到最大日期
                const maxDate = data.reduce((maxDate, item) => {
                    return new Date(item.ymd) > maxDate ? new Date(item.ymd) : maxDate;
                }, new Date(0)); // 初始值为最小日期

                // 2. 当前日期为最大日期加一天
                const currentDate = new Date(maxDate);
                currentDate.setDate(currentDate.getDate() + 1);

                // 3. 留存天数定义
                const retentionDays = {
                    nextDay: 1,
                    thirdDay: 2,
                    seventhDay: 6,
                    fifteenthDay: 14,
                    thirtiethDay: 29,
                };

                // 4. 用于存储有效注册人数和留存人数
                const retentionCounts = {
                    nextDay: { total: 0, retained: 0 },
                    thirdDay: { total: 0, retained: 0 },
                    seventhDay: { total: 0, retained: 0 },
                    fifteenthDay: { total: 0, retained: 0 },
                    thirtiethDay: { total: 0, retained: 0 },
                };

                // 5. 计算留存率
                data.forEach(item => {
                    const regDate = new Date(item.ymd);
                    console.log('当前日期',currentDate)
                    console.log('计算日期',regDate)
                    console.log('相差值',this.dateDiff(currentDate, regDate))

                    // 次日留存率
                    if (this.dateDiff(currentDate, regDate) >= retentionDays.nextDay) {
                        retentionCounts.nextDay.total += item.reg_num;
                        retentionCounts.nextDay.retained += item.day_2_num;
                    }

                    // 三日留存率
                    if (this.dateDiff(currentDate, regDate) >= retentionDays.thirdDay) {
                        retentionCounts.thirdDay.total += item.reg_num;
                        retentionCounts.thirdDay.retained += item.day_3_num;
                    }

                    // 七日留存率
                    if (this.dateDiff(currentDate, regDate) >= retentionDays.seventhDay) {
                        retentionCounts.seventhDay.total += item.reg_num;
                        retentionCounts.seventhDay.retained += item.day_7_num;
                    }

                    // 十五日留存率
                    if (this.dateDiff(currentDate, regDate) >= retentionDays.fifteenthDay) {
                        retentionCounts.fifteenthDay.total += item.reg_num;
                        retentionCounts.fifteenthDay.retained += item.day_15_num;
                    }

                    // 三十日留存率
                    if (this.dateDiff(currentDate, regDate) >= retentionDays.thirtiethDay) {
                        retentionCounts.thirtiethDay.total += item.reg_num;
                        retentionCounts.thirtiethDay.retained += item.day_30_num;
                    }
                });

                // 6. 计算留存率
                this.nextDayRetention = calculatePercentage(retentionCounts.nextDay.retained, retentionCounts.nextDay.total);
                this.thirdDayRetention = calculatePercentage(retentionCounts.thirdDay.retained, retentionCounts.thirdDay.total);
                this.seventhDayRetention = calculatePercentage(retentionCounts.seventhDay.retained, retentionCounts.seventhDay.total);
                this.fifteenthDayRetention = calculatePercentage(retentionCounts.fifteenthDay.retained, retentionCounts.fifteenthDay.total);
                this.thirtiethDayRetention = calculatePercentage(retentionCounts.thirtiethDay.retained, retentionCounts.thirtiethDay.total);
            },
            dateDiff(date1, date2) {
                const diffTime = Math.abs(date1 - date2);
                return Math.ceil(diffTime / (1000 * 60 * 60 * 24)); // 返回天数差
            }
        },
        mounted: function () {
            var _this = this;

            layui.use(['form', 'table'], function () {
                var $ = layui.jquery,
                    form = layui.form,
                    table = layui.table,
                    laydate = layui.laydate;

                laydate.render({
                    elem: '#createTime0',
                    value: getYmd(0)
                });
                laydate.render({
                    elem: '#createTime1',
                    value: getYmd(1)
                });

                var liucunlv = function(row, field) {
                    var all = row.reg_num;
                    var thisDayLiucun = row[field];
                    if (all === 0 || thisDayLiucun === 0) return '-';
                    return thisDayLiucun + ' <span class="percentage">' + calculatePercentage(thisDayLiucun, all) + '%</span>';
                };

                var reload = function() {
                    table.render({
                        where: form.val('table-search'),
                        elem: '#currentTableId',
                        url: '/admin/memberKeepPay/paginate',
                        defaultToolbar: ['filter', 'print'],
                        cols: [[
                            {type: "checkbox", width: 50},
                            {field: 'ymd', title: '日期', width: 160},
                            {field: 'reg_num', title: '注册人数'},
                            {field: 'day_2_num', title: '第2日留存', templet: function(row) { return liucunlv(row, 'day_2_num'); }},
                            {field: 'day_3_num', title: '第3日留存', templet: function(row) { return liucunlv(row, 'day_3_num'); }},
                            {field: 'day_7_num', title: '第7日留存', templet: function(row) { return liucunlv(row, 'day_7_num'); }},
                            {field: 'day_15_num', title: '第15日留存', templet: function(row) { return liucunlv(row, 'day_15_num'); }},
                            {field: 'day_30_num', title: '第30日留存', templet: function(row) { return liucunlv(row, 'day_30_num'); }},
                        ]],
                        limits: [10, 15, 20, 25, 50, 100],
                        limit: 15,
                        page: true,
                        skin: 'line',
                        done: function(res, curr, count) {
                            // 计算留存率
                            _this.calculateRetentionRates(res.data);
                        }
                    });
                };



                reload();

                form.on('submit(data-search-btn)', function () {
                    reload();
                    return false;
                });
            });
        }
    });
</script>
</body>
</html>